import { defineStore } from 'pinia';

import type { RouteRecordNormalized } from 'vue-router';
import defaultSettings from '@/config/settings.json';
import { AppState } from './types';

// @ts-ignore
const useAppStore = defineStore('app', {
  state: (): AppState => ({
    ...defaultSettings,
    route: [],
    // 窗口视图大小
    windowSizeObserver: {
      width: 0,
      height: 0,
    },
  }),

  getters: {
    appRoute(state: AppState): RouteRecordNormalized[] {
      return state.route as unknown as RouteRecordNormalized[]
    },
    appCurrentSetting(state: AppState): AppState {
      return { ...state };
    },
    appDevice(state: AppState) {
      return state.device;
    },
    appAsyncMenus(state: AppState): RouteRecordNormalized[] {
      return state.serverMenu as unknown as RouteRecordNormalized[];
    },
  },
  persist: true,

  actions: {
    updateRoute(route: RouteRecordNormalized[]) {
      this.route = route
    },
    updateWindowSizeObserver({
      width,
      height,
    }: {
      width: number;
      height: number;
    }) {
      this.windowSizeObserver = {
        width,
        height,
      };
    },
    // Update app settings
    updateSettings(partial: Partial<AppState>) {
      // @ts-ignore-next-line
      this.$patch(partial);
    },

    // Change theme color
    toggleTheme(dark: boolean) {
      if (dark) {
        this.theme = 'dark';
        document.body.setAttribute('arco-theme', 'dark');
      } else {
        this.theme = 'light';
        document.body.removeAttribute('arco-theme');
      }
    },
    toggleDevice(device: string) {
      this.device = device;
    },
    toggleMenu(value: boolean) {
      this.hideMenu = value;
    },
  },
});

export default useAppStore;
